<template>
  <div class="school-info-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <h1 class="page-title">
          <BankOutlined />
          我的学校
        </h1>
        <div class="header-stats">
          <div class="stat-item">
            <span class="stat-number">{{ schoolList.length }}</span>
            <span class="stat-label">管理学校</span>
          </div>
          <div class="stat-item">
            <span class="stat-number">{{ totalUsers }}</span>
            <span class="stat-label">总用户数</span>
          </div>
          <div class="stat-item">
            <span class="stat-number">{{ totalCampuses }}</span>
            <span class="stat-label">总校区数</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 学校卡片区域 -->
    <div class="schools-container">
      <a-skeleton :loading="loading" active :paragraph="{ rows: 4 }">
        <div v-if="schoolList.length > 0" class="schools-grid">
          <div v-for="school in schoolList" :key="school.id" class="school-card">
            <!-- 卡片头部 -->
            <div class="card-header">
              <div class="school-basic">
                <a-avatar
                  :src="school.schoolAvatar"
                  :size="56"
                  shape="square"
                  class="school-avatar"
                >
                  <template #icon>
                    <BankOutlined />
                  </template>
                </a-avatar>
                <div class="school-info">
                  <h3 class="school-name">{{ school.schoolName }}</h3>
                  <p class="school-campus">{{ school.campuses }}</p>
                </div>
              </div>
              <a-tag
                :color="school.schoolStatus === 'active' ? 'success' : 'error'"
                class="status-tag"
              >
                {{ school.schoolStatus === 'active' ? '正常运营' : '暂停运营' }}
              </a-tag>
            </div>

            <!-- 统计卡片区 -->
            <div class="stats-section">
              <div class="stat-card user-stats" @click="handleShowUserList(school)">
                <div class="stat-icon">
                  <UserOutlined />
                </div>
                <div class="stat-content">
                  <div class="stat-number">{{ school.userCount }}</div>
                  <div class="stat-label">用户数量</div>
                </div>
              </div>

              <div class="stat-card campus-stats">
                <div class="stat-icon">
                  <EnvironmentOutlined />
                </div>
                <div class="stat-content">
                  <div class="stat-number">{{ school.campusCount }}</div>
                  <div class="stat-label">校区数量</div>
                </div>
              </div>

              <div class="stat-card admin-stats">
                <div class="stat-icon">
                  <TeamOutlined />
                </div>
                <div class="stat-content">
                  <div class="stat-number">{{ school.schoolAdmins.length }}</div>
                  <div class="stat-label">管理员</div>
                </div>
              </div>
            </div>

            <!-- 详细信息区 -->
            <div class="detail-section">
              <div class="detail-item">
                <label>创建时间：</label>
                <span>{{ formatDate(school.createdTime) }}</span>
              </div>

              <div class="detail-item">
                <label>管理员：</label>
                <div class="admin-list">
                  <a-tag
                    v-for="admin in school.schoolAdmins"
                    :key="admin"
                    color="blue"
                    size="small"
                  >
                    {{ admin }}
                  </a-tag>
                </div>
              </div>

              <div v-if="hasLocation(school)" class="detail-item location-item">
                <label>地理位置：</label>
                <div class="location-content">
                  <span class="coordinates">
                    {{ school.longitude.toFixed(4) }}, {{ school.latitude.toFixed(4) }}
                  </span>
                  <a-button
                    type="link"
                    size="small"
                    @click="handleShowMap(school)"
                    class="view-map-btn"
                  >
                    <GlobalOutlined />
                    查看地图
                  </a-button>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 空状态 -->
        <div v-else-if="!loading" class="empty-state">
          <a-empty description="暂无管理的学校" />
        </div>
      </a-skeleton>
    </div>

    <!-- 地图弹窗 -->
    <a-modal
      v-model:open="mapVisible"
      :title="`${currentSchool?.schoolName} - 位置信息`"
      :footer="null"
      width="600px"
      @after-close="handleMapModalClose"
    >
      <div class="map-container">
        <div id="schoolLocationMap" style="height: 350px; width: 100%"></div>
      </div>
    </a-modal>

    <!-- 用户列表弹窗 -->
    <a-modal
      v-model:open="userListVisible"
      :title="`${currentSchoolForUsers?.schoolName} - 用户列表`"
      width="1400px"
      :footer="null"
      @after-close="handleUserListModalClose"
      :bodyStyle="{ padding: '20px' }"
    >
      <div class="user-list-modal">
        <!-- 搜索区域 -->
        <div class="search-section">
          <a-input
            v-model:value="userSearchKeyword"
            placeholder="请输入用户昵称进行搜索..."
            allow-clear
            @change="handleUserSearch"
            class="search-input"
          >
            <template #prefix>
              <SearchOutlined />
            </template>
          </a-input>
        </div>

        <!-- 用户列表 -->
        <div class="users-content">
          <a-table
            :columns="userColumns"
            :data-source="modalUserList"
            :loading="userModalLoading"
            :pagination="userPagination"
            @change="handleUserTableChange"
            row-key="id"
            size="small"
            :scroll="{ x: 1200 }"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'avatar'">
                <a-avatar :src="record.avatar" :size="32">
                  <template #icon>
                    <UserOutlined />
                  </template>
                </a-avatar>
              </template>

              <template v-else-if="column.key === 'userType'">
                <a-tag :color="getUserTypeColor(record.userType)">
                  {{ getUserTypeText(record.userType) }}
                </a-tag>
              </template>

              <template v-else-if="column.key === 'userStatus'">
                <a-tag :color="record.userStatus === 'normal' ? 'success' : 'error'">
                  {{ record.userStatus === 'normal' ? '正常' : '封禁' }}
                </a-tag>
              </template>

              <template v-else-if="column.key === 'sex'">
                <a-tag :color="record.sex === 1 ? 'blue' : record.sex === 2 ? 'pink' : 'default'">
                  {{ getSexText(record.sex) }}
                </a-tag>
              </template>

              <template v-else-if="column.key === 'lastLoginTime'">
                {{ formatUserLoginTime(record.lastLoginTime) }}
              </template>

              <template v-else-if="column.key === 'actions'">
                <a-button
                  :type="record.userStatus === 'normal' ? 'default' : 'primary'"
                  :danger="record.userStatus === 'normal'"
                  size="small"
                  @click="handleToggleUserStatus(record)"
                  :loading="record.statusLoading"
                >
                  {{ record.userStatus === 'normal' ? '封禁' : '解封' }}
                </a-button>
              </template>
            </template>
          </a-table>
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, nextTick, reactive } from 'vue'
import { message } from 'ant-design-vue'
import {
  BankOutlined,
  UserOutlined,
  EnvironmentOutlined,
  TeamOutlined,
  GlobalOutlined,
  SearchOutlined,
} from '@ant-design/icons-vue'
import { schoolService } from '@/api/school'
import { userService, type UserPageParams } from '@/api/user'
import { createReadonlyMap, destroyMap } from '@/utils/mapUtils'
import type { SchoolWithStats, User } from '@/types'

// 状态管理
const loading = ref(false)
const mapVisible = ref(false)
const schoolList = ref<SchoolWithStats[]>([])
const currentSchool = ref<SchoolWithStats | null>(null)
let currentMap: any = null

// 用户列表弹窗相关状态
const userListVisible = ref(false)
const currentSchoolForUsers = ref<SchoolWithStats | null>(null)
const userSearchKeyword = ref('')
const userModalLoading = ref(false)
const modalUserList = ref<User[]>([])

// 用户分页配置
const userPagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 个用户`,
})

// 搜索防抖定时器
let userSearchTimeout: ReturnType<typeof setTimeout> | null = null

// 用户表格列配置
const userColumns = [
  {
    title: '头像',
    key: 'avatar',
    dataIndex: 'avatar',
    width: 70,
    align: 'center' as const,
    fixed: 'left' as const,
  },
  {
    title: '昵称',
    key: 'nickName',
    dataIndex: 'nickName',
    width: 120,
    ellipsis: true,
    fixed: 'left' as const,
  },
  {
    title: '用户类型',
    key: 'userType',
    dataIndex: 'userType',
    width: 100,
    align: 'center' as const,
  },
  {
    title: '用户状态',
    key: 'userStatus',
    dataIndex: 'userStatus',
    width: 100,
    align: 'center' as const,
  },
  {
    title: '学号',
    key: 'studentId',
    dataIndex: 'studentId',
    width: 120,
    ellipsis: true,
  },
  {
    title: '星遇号',
    key: 'stellarMeetCode',
    dataIndex: 'stellarMeetCode',
    width: 120,
    align: 'center' as const,
  },
  {
    title: '手机号',
    key: 'phone',
    dataIndex: 'phone',
    width: 120,
    ellipsis: true,
  },
  {
    title: '邮箱',
    key: 'email',
    dataIndex: 'email',
    width: 180,
    ellipsis: true,
  },
  {
    title: '性别',
    key: 'sex',
    dataIndex: 'sex',
    width: 80,
    align: 'center' as const,
  },
  {
    title: '年级',
    key: 'grade',
    dataIndex: 'grade',
    width: 100,
    align: 'center' as const,
  },
  {
    title: '登录次数',
    key: 'loginCount',
    dataIndex: 'loginCount',
    width: 100,
    align: 'center' as const,
  },
  {
    title: '上次登录',
    key: 'lastLoginTime',
    dataIndex: 'lastLoginTime',
    width: 120,
    align: 'center' as const,
  },
  {
    title: '操作',
    key: 'actions',
    width: 100,
    align: 'center' as const,
    fixed: 'right' as const,
  },
]

// 计算统计数据
const totalUsers = computed(() => {
  return schoolList.value.reduce((total, school) => total + school.userCount, 0)
})

const totalCampuses = computed(() => {
  return schoolList.value.reduce((total, school) => total + school.campusCount, 0)
})

// 页面加载时获取数据
onMounted(() => {
  loadSchoolList()
})

// 加载学校列表
const loadSchoolList = async () => {
  try {
    loading.value = true
    const result = await schoolService.getSchoolListByUser()
    schoolList.value = result || []
  } catch (error) {
    console.error('加载学校列表失败:', error)
    message.error('加载学校列表失败')
  } finally {
    loading.value = false
  }
}

// 检查是否有位置信息
const hasLocation = (school: SchoolWithStats) => {
  return !!(school.longitude && school.latitude)
}

// 显示地图
const handleShowMap = async (school: SchoolWithStats) => {
  if (!hasLocation(school)) {
    message.warning('该学校未设置地理位置')
    return
  }

  currentSchool.value = school
  mapVisible.value = true

  await nextTick()
  try {
    currentMap = await createReadonlyMap('schoolLocationMap', {
      longitude: school.longitude,
      latitude: school.latitude,
      title: school.schoolName,
    })
  } catch (error) {
    console.error('地图加载失败:', error)
    message.error('地图加载失败')
  }
}

// 地图弹窗关闭
const handleMapModalClose = () => {
  destroyMap()
  currentMap = null
  currentSchool.value = null
}

// 格式化日期
const formatDate = (dateString: string) => {
  if (!dateString) return '暂无'

  try {
    const date = new Date(dateString)
    return date.toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: 'long',
      day: 'numeric',
    })
  } catch {
    return dateString
  }
}

// 显示用户列表
const handleShowUserList = async (school: SchoolWithStats) => {
  currentSchoolForUsers.value = school
  userListVisible.value = true
  userSearchKeyword.value = ''
  userPagination.current = 1
  await loadUserList()
}

// 加载用户列表
const loadUserList = async () => {
  if (!currentSchoolForUsers.value) return

  try {
    userModalLoading.value = true
    const params: UserPageParams = {
      page: userPagination.current,
      pageSize: userPagination.pageSize,
      schoolId: currentSchoolForUsers.value.id,
      nickName: userSearchKeyword.value || undefined,
    }

    const result = await userService.getUserPage(params)
    modalUserList.value = (result.result || []).map((user) => ({
      ...user,
      statusLoading: false, // 添加状态切换加载状态
    }))
    userPagination.total = result.total || 0
  } catch (error) {
    console.error('加载用户列表失败:', error)
    message.error('加载用户列表失败')
  } finally {
    userModalLoading.value = false
  }
}

// 处理用户搜索
const handleUserSearch = () => {
  if (userSearchTimeout) {
    clearTimeout(userSearchTimeout)
  }

  userSearchTimeout = setTimeout(() => {
    userPagination.current = 1
    loadUserList()
  }, 500)
}

// 处理用户表格变化
const handleUserTableChange = (pagination: any) => {
  userPagination.current = pagination.current
  userPagination.pageSize = pagination.pageSize
  loadUserList()
}

// 处理用户状态切换
const handleToggleUserStatus = async (record: User & { statusLoading?: boolean }) => {
  try {
    record.statusLoading = true

    await userService.toggleUserStatus(record.id)

    // 切换本地状态
    record.userStatus = record.userStatus === 'normal' ? 'banned' : 'normal'

    message.success(`用户${record.userStatus === 'normal' ? '解封' : '封禁'}成功`)

    // 更新学校统计中的用户数量（如果需要的话）
    if (currentSchoolForUsers.value) {
      // 可以选择重新加载学校列表或者手动更新数量
    }
  } catch (error) {
    console.error('用户状态切换失败:', error)
    message.error('操作失败，请重试')
  } finally {
    record.statusLoading = false
  }
}

// 处理用户列表弹窗关闭
const handleUserListModalClose = () => {
  currentSchoolForUsers.value = null
  modalUserList.value = []
  userSearchKeyword.value = ''
  userPagination.current = 1
  userPagination.total = 0

  if (userSearchTimeout) {
    clearTimeout(userSearchTimeout)
    userSearchTimeout = null
  }
}

// 格式化用户登录时间
const formatUserLoginTime = (lastLoginTime?: string) => {
  if (!lastLoginTime) return '从未登录'

  try {
    const date = new Date(lastLoginTime)
    const now = new Date()
    const diff = now.getTime() - date.getTime()
    const days = Math.floor(diff / (1000 * 60 * 60 * 24))

    if (days === 0) return '今天'
    if (days === 1) return '昨天'
    if (days < 7) return `${days}天前`
    if (days < 30) return `${Math.floor(days / 7)}周前`
    return `${Math.floor(days / 30)}月前`
  } catch {
    return '无效时间'
  }
}

// 获取用户类型颜色
const getUserTypeColor = (userType: string) => {
  // 根据用户类型返回不同的颜色
  switch (userType) {
    case 'wechat':
      return 'green'
    case 'anonymous':
      return 'orange'
    default:
      return 'default'
  }
}

// 获取用户类型文本
const getUserTypeText = (userType: string) => {
  // 根据用户类型返回不同的文本
  switch (userType) {
    case 'wechat':
      return '微信用户'
    case 'anonymous':
      return '匿名用户'
    default:
      return '未知类型'
  }
}

// 获取性别文本
const getSexText = (sex: number) => {
  // 根据性别返回不同的文本
  switch (sex) {
    case 1:
      return '男'
    case 2:
      return '女'
    default:
      return '未知'
  }
}
</script>

<style scoped lang="scss">
.school-info-page {
  padding: 24px;
  min-height: 100vh;
  background: #f5f7fa;
}

.page-header {
  background: url('https://lanyun-tc.oss-cn-guangzhou.aliyuncs.com/003.jpeg');
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  border-radius: 12px;
  padding: 32px;
  margin-bottom: 24px;
  color: white;
  position: relative;
  overflow: hidden;

  // 第二层背景，用于淡入淡出效果
  &::after {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-image: url('https://lanyun-tc.oss-cn-guangzhou.aliyuncs.com/01.png');
    background-size: cover;
    background-position: center;
    background-repeat: no-repeat;
    opacity: 0;
    animation: fadeInOut 8s ease-in-out infinite;
    z-index: 0;
  }

  // 添加背景图片的覆盖层，确保文字可读性
  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: linear-gradient(135deg, rgba(102, 126, 234, 0.4) 0%, rgba(118, 75, 162, 0.4) 100%);
    z-index: 1;
  }

  .header-content {
    position: relative;
    z-index: 2;
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-wrap: wrap;
    gap: 24px;
  }

  .page-title {
    margin: 0;
    font-size: 28px;
    font-weight: 600;
    display: flex;
    align-items: center;
    gap: 12px;
    color: white;
    text-shadow: 0 2px 4px rgba(0, 0, 0, 0.5);
  }

  .header-stats {
    display: flex;
    gap: 32px;

    .stat-item {
      text-align: center;

      .stat-number {
        display: block;
        font-size: 24px;
        font-weight: 700;
        margin-bottom: 4px;
        color: white;
        text-shadow: 0 2px 4px rgba(0, 0, 0, 0.5);
      }

      .stat-label {
        font-size: 14px;
        color: rgba(255, 255, 255, 0.95);
        text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
      }
    }
  }
}

// 背景淡入淡出动画
@keyframes fadeInOut {
  0%,
  20% {
    opacity: 0;
  }
  30%,
  70% {
    opacity: 1;
  }
  80%,
  100% {
    opacity: 0;
  }
}

.schools-container {
  .schools-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(400px, 1fr));
    gap: 24px;
  }

  .school-card {
    background: white;
    border-radius: 12px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
    overflow: hidden;
    transition: all 0.3s ease;

    &:hover {
      transform: translateY(-4px);
      box-shadow: 0 8px 32px rgba(0, 0, 0, 0.12);
    }

    .card-header {
      padding: 24px;
      border-bottom: 1px solid #f0f0f0;
      display: flex;
      justify-content: space-between;
      align-items: flex-start;

      .school-basic {
        display: flex;
        gap: 16px;
        align-items: center;
        flex: 1;

        .school-avatar {
          border: 2px solid #f0f0f0;
        }

        .school-info {
          .school-name {
            margin: 0 0 4px 0;
            font-size: 18px;
            font-weight: 600;
            color: #262626;
          }

          .school-campus {
            margin: 0;
            font-size: 14px;
            color: #666;
          }
        }
      }

      .status-tag {
        font-weight: 500;
      }
    }

    .stats-section {
      padding: 20px 24px;
      border-bottom: 1px solid #f0f0f0;
      display: grid;
      grid-template-columns: repeat(3, 1fr);
      gap: 16px;

      .stat-card {
        display: flex;
        align-items: center;
        gap: 12px;
        padding: 16px;
        background: #fafafa;
        border-radius: 8px;
        transition: all 0.3s ease;

        &:hover {
          background: #f0f8ff;
          transform: translateY(-2px);
        }

        .stat-icon {
          width: 36px;
          height: 36px;
          border-radius: 8px;
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 16px;
          color: white;
        }

        .stat-content {
          .stat-number {
            font-size: 18px;
            font-weight: 600;
            margin-bottom: 2px;
          }

          .stat-label {
            font-size: 12px;
            color: #666;
          }
        }

        &.user-stats {
          .stat-icon {
            background: linear-gradient(135deg, #667eea, #764ba2);
          }
          .stat-number {
            color: #667eea;
          }

          // 添加可点击样式
          cursor: pointer;

          &:hover {
            background: #e6f7ff;
            border-color: #1890ff;
            transform: translateY(-4px);
            box-shadow: 0 4px 16px rgba(24, 144, 255, 0.2);
          }
        }

        &.campus-stats {
          .stat-icon {
            background: linear-gradient(135deg, #f093fb, #f5576c);
          }
          .stat-number {
            color: #f5576c;
          }
        }

        &.admin-stats {
          .stat-icon {
            background: linear-gradient(135deg, #4facfe, #00f2fe);
          }
          .stat-number {
            color: #4facfe;
          }
        }
      }
    }

    .detail-section {
      padding: 24px;

      .detail-item {
        display: flex;
        align-items: flex-start;
        margin-bottom: 16px;

        &:last-child {
          margin-bottom: 0;
        }

        label {
          width: 80px;
          color: #666;
          font-size: 14px;
          margin-right: 12px;
          flex-shrink: 0;
        }

        span {
          color: #262626;
          font-size: 14px;
        }

        .admin-list {
          display: flex;
          flex-wrap: wrap;
          gap: 4px;
        }

        &.location-item {
          .location-content {
            display: flex;
            flex-direction: column;
            gap: 8px;

            .coordinates {
              color: #262626;
              font-size: 14px;
              font-family: monospace;
            }

            .view-map-btn {
              padding: 0;
              height: auto;
              font-size: 12px;
              align-self: flex-start;
            }
          }
        }
      }
    }
  }

  .empty-state {
    text-align: center;
    padding: 80px 0;
    background: white;
    border-radius: 12px;
  }
}

.map-container {
  #schoolLocationMap {
    border-radius: 8px;
    overflow: hidden;
  }
}

// 响应式设计
@media (max-width: 1200px) {
  .schools-grid {
    grid-template-columns: repeat(auto-fill, minmax(350px, 1fr)) !important;
  }
}

@media (max-width: 768px) {
  .school-info-page {
    padding: 16px;
  }

  .page-header {
    padding: 24px;

    .header-content {
      flex-direction: column;
      text-align: center;

      .header-stats {
        gap: 24px;
      }
    }
  }

  .schools-grid {
    grid-template-columns: 1fr !important;
  }

  .stats-section {
    grid-template-columns: 1fr !important;
  }
}

// 用户列表弹窗样式
.user-list-modal {
  .search-section {
    margin-bottom: 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .search-input {
      width: 350px;
    }
  }

  .users-content {
    :deep(.ant-table) {
      .ant-table-thead > tr > th {
        background-color: #fafafa;
        font-weight: 600;
        font-size: 13px;
        padding: 12px 8px;
        white-space: nowrap;
      }

      .ant-table-tbody > tr {
        &:hover > td {
          background-color: #f5f7fa;
        }

        td {
          padding: 10px 8px;
          font-size: 12px;

          .ant-avatar {
            border: 1px solid #f0f0f0;
          }

          .ant-tag {
            margin: 0;
            font-size: 11px;
            border-radius: 4px;
          }

          .ant-btn {
            font-size: 11px;
            height: 28px;
            padding: 0 8px;
          }
        }
      }

      .ant-table-fixed-left,
      .ant-table-fixed-right {
        box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
      }

      .ant-table-pagination {
        margin-top: 20px;
        text-align: center;
      }
    }
  }
}
</style>